package com.example.monitorsms.utils;

import android.os.Environment;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class UuidUtils {
    // 配置文件路径
    public static final String filePath = Environment.getExternalStorageDirectory() + File.separator + "sms.txt";

    public static boolean isUuidExit() {
        File file = new File(filePath);
        if (file.exists()) {
            return true;
        } else {
            try {
                file.createNewFile();
                uuidJson();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static boolean uuidJson() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("uuid", getUUID());
            // 修改内容写入配置文件
            FileUtils.writeTxtFile(jsonObject.toString(), filePath);
            // 重新读取配置文件内容
            initUuid();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String initUuid() {
        String configMessage = FileUtils.txt2String(filePath);
        if (configMessage.equals("")) {
            LogUtils.e("uuid", "文件不存在");
            return "";
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(configMessage);
            return jsonObject.get("uuid") + "";
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e("uuid", "UUid返回异常！");
            return "";
        }
    }
}
